<script setup>
import {ref} from 'vue'
import{loginUser} from '@/api/user'
import router from '@/router'
import { ElMessage } from 'element-plus'

//定义表单
const loginForm=ref({
  username:'',
  password:''
})

//效验规则
const loginRules =ref({
  username:[
    {required: true,message:'账号不能为空!',trigger:'blur'},
    {min: 3,max: 20,message:'账号长度在3-20位之间!',trigger:'blur'},
  ],
  password:[
    {required: true,message:'密码不能为空!',trigger:'blur'},
    {min: 3,max: 60,message:'密码长度在3-60位之间!',trigger:'blur'},
  ]
})

//关联表单
const loginFormRef=ref(null)
// 登录方法
const submitForm = async () => {
  if (!loginFormRef.value) return // 修复引用检查
  await loginFormRef.value.validate(async(valid, fields) => {
    if (valid) {
      let result=await loginUser(loginForm.value)
      if(result.code==200){
        localStorage.setItem('userInfo',JSON.stringify(result.data))
        ElMessage.success('登录成功!')
        router.push('/')
      }else{
        ElMessage.error('登录失败!')
      }
    }else{
      console.log('效验失败!!!',fields)
    }
  }
  )
}

</script>
<!-- html -->
<template>
  <el-form
    ref="loginFormRef"
    style="max-width: 600px"
    :model="loginForm"
    status-icon
    :rules="loginRules"
    label-width="auto"
    
  >
    <el-form-item label="账号" prop="username">
      <el-input v-model="loginForm.username" placeholder="请输入账号" :show-password="false"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm()">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>
<!-- css样式 -->
<style scoped>

</style>